package com.example.wiki.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.wiki.entity.Category;
import com.example.wiki.entity.req.CategoryQueryReq;
import com.example.wiki.entity.resp.CategoryQueryResp;
import com.example.wiki.entity.resp.CommonResp;
import com.example.wiki.entity.resp.PageResp;
import com.example.wiki.service.ICategoryService;
import com.example.wiki.util.CopyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 电子书分类 前端控制器
 * </p>
 *
 * @author jerry
 * @since 2024-10-08
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    //获取一级分类信息：parent为0
    @GetMapping("/getParents")  // http://localhost:8088/category/getParents
    public CommonResp getParents(CategoryQueryReq req) {
        //条件
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("parent", 0);
        //查询
        List<Category> list = categoryService.list(wrapper);
        List<CategoryQueryResp> categoryQueryRespList = CopyUtil.copyList(list, CategoryQueryResp.class);
        //存放响应的数据
        CommonResp<List<CategoryQueryResp>> resp = new CommonResp<>();
        resp.setContent(categoryQueryRespList);
        return resp;
    }

    //没有分页查询-查询所有
    @GetMapping("/getCategoryList") // http://localhost:8088/category/getCategoryList
    public CommonResp getCategoryList(CategoryQueryReq req) {
        List<CategoryQueryResp> categoryList = categoryService.getCategoryList(req);
        CommonResp<List<CategoryQueryResp>> resp = new CommonResp<>();
        resp.setContent(categoryList);
        return resp;
    }

    //分页查询
    @GetMapping("/getCategoryListByPage")  // http://localhost:8088/category/getCategoryListByPage
    public CommonResp getCategoryListByPage(CategoryQueryReq req) {
        PageResp<CategoryQueryResp> repsPage = categoryService.getCategoryListByPage(req);
        CommonResp<PageResp<CategoryQueryResp>> resp = new CommonResp<>();
        resp.setContent(repsPage);
        return resp;
    }

    @PostMapping("/save")
    public CommonResp save(@RequestBody CategoryQueryReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        boolean saveOrUpdate = categoryService.saveOrUpdate(category);
        CommonResp resp = new CommonResp<>();
        resp.setSuccess(saveOrUpdate);
        return resp;
    }

    @GetMapping("/remove")
    public CommonResp remove(int id) {
        boolean remove = categoryService.removeById(id);
        CommonResp<Object> resp = new CommonResp<>();
        resp.setSuccess(remove);
        return resp;
    }

}
